package com.johnson.news.model.remote;

import android.text.TextUtils;

import com.johnson.news.util.Utils;
import com.youmbe.library.util.Constants;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitFactory {

    private static Retrofit retrofit;

    public static Retrofit getRetrofit() {
        if (retrofit == null) {

            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);

            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
            httpClient.connectTimeout(10, TimeUnit.SECONDS);
            httpClient.readTimeout(10, TimeUnit.SECONDS);
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request origianl = chain.request();
                    HttpUrl url = origianl.url().newBuilder()
                            .addQueryParameter("authtoken", Utils.getToken())
                            .build();

                    Request.Builder request = origianl.newBuilder();
//                    request.addHeader("auth_token", Utils.getToken());
                    return chain.proceed(request.url(url).build());
                }
            });
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    Response response = chain.proceed(request);

                    MediaType mediaType = response.body().contentType();
                    String content = response.body().string();

//                    // 对返回code统一拦截
//                    if (response != null && !TextUtils.isEmpty(content)) {
////                        if (content.contains("\"code\":402") && !content.contains("shop/cart/number")) {//todo 被挤下线，重新登录；融云单点登录未生效的话，此处被动提示
////                            EventBus.getDefault().post(new LoginMessage(false));
////                        }
//                    }
                    return response.newBuilder().body(ResponseBody.create(mediaType, content))
                            .build();
                }
            });
            httpClient.addInterceptor(logging);

            retrofit = new Retrofit.Builder()
                    .baseUrl(APIService.baseUrl)
                    .addConverterFactory(ScalarsConverterFactory.create())//不加的话，PartMap的参数会多一层引号
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(httpClient.build())
                    .build();
        }

        return retrofit;
    }

    public static <T> T getService(Class<T> service) {
        return getRetrofit().create(service);
    }
}
